#include <QUndoStack>
#include "Qt3DPicker.h"
#include "CmdManager.h"
#include "CylinderHandler.h"
#include "Cylinder.h"
#include "Operation/OpAdd.h"
#include "PointHandler.h"
#include "SendPointHandlerBase.h"
#include "Scene.h"
#include "QtOSGWidget.h"
#include "SelectHandler3D.h"
#include "Ucs.h"


CylinderHandler::CylinderHandler()
{
}

CylinderHandler::~CylinderHandler()
{
}

void CylinderHandler::input(const QVariant& data, const QString& rawInput, CommandSource cs)
{
	auto sph = getSendPointHandler();
	auto scene = getScene();
	auto widget = getWidget();
	if (data.type() == QVariant::Bool && !data.toBool())
	{
		emit finished();
		return;
	}

	if (status() == 0)
	{
		if (sph)
		{
			sph->setPointMask(CS_LBTNDOWN);
		}
		prompt(1, tr("指定基准点: "));
		return;
	}

	if (status() == 1)
	{
		if (data.type() == QVariant::Vector3D)
		{
			auto pt = data.value<QVector3D>();
			m_point = {pt.x(),pt.y(),pt.z()};
			prompt(4, tr("指定轴向[两点(0)/方向向量(1)]<0,0,1>:"));
		}
		return;
	}

	if (status() == 4)
	{
		if (data.type() == QVariant::Bool && data.toBool())
		{
			m_axis.set(0, 0, 1);
			prompt(2, tr("指定圆柱体直径:"));
			return;
		}
		if (data.type() == QVariant::Double)
		{
			if (data.toInt() == 0)
			{
				prompt(5, tr("指定起点: "));
			}
			else if (data.toInt() == 1)
			{
				prompt(7, tr("指定轴向向量: "));
			}
			return;
		}
		return;
	}

	if (status() == 5)
	{
		if (data.type() == QVariant::Vector3D)
		{
			auto pt = data.value<QVector3D>();
			m_start = { pt.x(),pt.y(),pt.z() };
			prompt(6, tr("指定终点: "));
		}
		return;
	}

	if (status() == 6)
	{
		if (data.type() == QVariant::Vector3D)
		{
			auto pt = data.value<QVector3D>();
			m_end = { pt.x(),pt.y(),pt.z() };
			m_axis = m_end - m_start;
			double len = m_axis.normalize();
			if (len == 0)
			{
				remark(tr("起点终点重合，无法指明轴向"));
				return;
			}
			prompt(2, tr("指定圆柱体直径:"));
		}
		return;
	}

	if (status() == 7)
	{
		if (data.type() == QVariant::Vector3D)
		{
			auto pt = data.value<QVector3D>();
			m_axis = { pt.x(),pt.y(),pt.z() };
			double len = m_axis.normalize();
			if (len == 0)
			{
				remark(tr("轴向向量不可以是0向量"));
				return;
			}
			prompt(2, tr("指定圆柱体直径:"));
		}
		return;
	}

	if (status() == 2)
	{
		if (data.type() == QVariant::Double)
		{
			m_diameter = data.toFloat();
			if (m_diameter <= 0)
			{
				remark(tr("圆柱体直径必须大于0"));
				emit finished();
				return;
			}
			prompt(3, tr("指定圆柱体的高:"));
		}
		return;
	}

	if (status() == 3)
	{
		if (data.type() == QVariant::Double)
		{
			auto height = data.toFloat();
			if (height <= 0)
			{
				remark(tr("圆柱体的高必须大于0"));
				emit finished();
				return;
			}
			auto cylinder = std::make_shared<Cylinder>(scene);
			cylinder->setBottomCenter(m_point);
			cylinder->setAxis(m_axis);
			cylinder->setRadius(m_diameter / 2.0);
			cylinder->setHeight(height);
			auto undoStack = scene->undoStack();
			undoStack->push(new OpAdd(cylinder->decompose()));
			emit finished();
		}
		return;
	}
}
